package com.dp.service.impl;

import com.dp.dto.Result;
import com.dp.entity.SeckillVoucher;
import com.dp.entity.VoucherOrder;
import com.dp.mapper.VoucherOrderMapper;
import com.dp.service.ISeckillVoucherService;
import com.dp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dp.utils.RedisIdWorker;
import com.dp.utils.SimpleRedisLock;
import com.dp.utils.UserHolder;
import org.springframework.aop.framework.AopContext;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Transactional
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private ISeckillVoucherService seckillVoucherService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedisIdWorker redisIdWorker;

    @Override
    public Result secKillVoucher(Long voucherId) {

        //查询优惠券
        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
        //判断秒杀是否开始
        if (voucher.getBeginTime().isAfter(LocalDateTime.now())) {
            return  Result.fail("秒杀尚未开始！");
        }

        //判断是否结束
        if (voucher.getEndTime().isBefore(LocalDateTime.now())) {
            return Result.fail("秒杀已经结束！");
        }
        Long userId = UserHolder.getUser().getId();

        //intern 返回字符串的规范表示，值一样时，返回的地址都是一样，都是同一个锁
//        synchronized (userId.toString().intern()) {
//            事务要想要生效，是因为spring对这个类做了动态代理拿到了当前类的代理对象

//                    需要拿到当前对象的代理对象

            //创建锁对象
        SimpleRedisLock redisLock = new SimpleRedisLock(stringRedisTemplate,"order"+userId);
            //获取锁
        boolean isLock = redisLock.tryLock(1200L);
            //锁范围：应该是用户id
        if (!isLock) {
            return Result.fail("不允许重复下单！");
        }
        try {
            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            return proxy.CreateVoucherOrder(voucherId, voucher);
        }finally {
            //关闭锁


            redisLock.unLock();
        }

//        }
    }
    @Transactional
    public  Result CreateVoucherOrder(Long voucherId, SeckillVoucher voucher) {
        //一人只能下一单
        Long userId = UserHolder.getUser().getId();
        //查询订单
        int count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
        //判断是否存在
        if (count>0) {
            return Result.fail("该用户已经购买过一次了！");
        }
        //判断库存是否充足
        if (voucher.getStock()<1) {
            return Result.fail("库存不足！");
        }
        //扣减库存
        boolean success = seckillVoucherService.update()
                .setSql("stock = stock -1")
                .eq("voucher_id", voucherId).gt("stock",0).update();
        if (!success) {
            return Result.fail("库存不足！");
        }
        //创建订单
        VoucherOrder voucherOrder = new VoucherOrder();
        //订单id，用户id，代金券id
        long orderId = redisIdWorker.nextId("order");
        voucherOrder.setId(orderId);
//        Long userId = UserHolder.getUser().getId();
        Long Id = 1L;

        voucherOrder.setUserId(Id);
        voucherOrder.setVoucherId(voucherId);
        //写入数据库
        save(voucherOrder);
        //返回订单id
        return Result.ok(orderId);

    }

}
